<template>
    <div>
        <el-text size="large">商品信息</el-text>
        <el-divider style="margin: 10px 0;"></el-divider>
        <el-form :model="queryForm" label-width="120px" style="max-width: 100%; margin: 0 auto;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="商品ID">
                        <el-input-number v-model="queryForm.goods_id as number" :min="0" :step="1" step-strictly placeholder="请输入ID" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="名字">
                        <el-autocomplete v-model="queryForm.goods_name" :fetch-suggestions="fetchSuggestions('goods_name')" placeholder="请输入商品名字"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="类别">
                        <el-autocomplete v-model="queryForm.goods_type" :fetch-suggestions="fetchSuggestions('goods_type')" placeholder="请选择类别"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="备注">
                        <el-autocomplete v-model="queryForm.remarks" :fetch-suggestions="fetchSuggestions('remarks')" placeholder="请输入备注"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" @click="searchGoods" :loading="loading" :icon="Search">查询</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="success" @click="openAddDialog" :icon="Plus">新增</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-divider style="margin: 10px 0;"></el-divider>
        
        <el-table :data="paginatedGoodsList" v-if="paginatedGoodsList.length > 0">
            <el-table-column prop="goods_id" label="商品ID" sortable></el-table-column>
            <el-table-column prop="goods_name" label="名字" sortable></el-table-column>
            <el-table-column prop="goods_type" label="类别" sortable></el-table-column>
            <el-table-column prop="remarks" label="备注" sortable></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-container style="width: 4.5rem;">
                        <el-button type="primary" :icon="Edit" circle @click="openEditDialog(scope.row)"></el-button>
                        <el-button type="danger" :icon="Delete" circle @click="openDeleteDialog(scope.row)"></el-button>
                    </el-container>
                </template>
            </el-table-column>
        </el-table>
        <el-empty v-else description="没找到数据呢，亲~"></el-empty>
        <el-pagination
            v-if="total > 0"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
        <AddDialog ref="addGoodsDialog" @refresh="searchGoods" />
        <EditDialog ref="editGoodsDialog" @refresh="searchGoods" />
        <DeleteDialog ref="deleteGoodsDialog" @refresh="searchGoods" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import AddDialog from '@/components/AddDialog.vue';
import EditDialog from '@/components/EditDialog.vue';
import DeleteDialog from '@/components/DeleteDialog.vue';
import type { GoodsQueryForm, Goods, FormItem } from '@/types/interface';
import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue';

const queryForm = reactive<GoodsQueryForm>({
    goods_id: null as any,
    goods_name: '',
    goods_type: '',
    remarks: ''
});

const goodsList = ref<Goods[]>([
    { goods_id: 1, goods_name: '商品A', goods_type: '类型1', remarks: '备注A' },
    { goods_id: 2, goods_name: '商品B', goods_type: '类型2', remarks: '备注B' },
    { goods_id: 3, goods_name: '商品C', goods_type: '类型3', remarks: '备注C' }
]);
const total = ref(goodsList.value.length);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 分页数据
const paginatedGoodsList = computed(() => {
    if (!goodsList.value || goodsList.value.length === 0) {
        return [];
    }
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return goodsList.value.slice(start, end);
});

// 获取建议
function fetchSuggestions(field: keyof GoodsQueryForm): (queryString: string, cb: (suggestions: { value: string }[]) => void) => void {
    return async (queryString: string, cb: (suggestions: { value: string }[]) => void) => {
        if (!queryString) {
            cb([]);
            return;
        }
        try {
            const response = await axios.get(`/api/goods/suggestions`, {
                params: { field, query: queryString }
            });
            cb(response.data.map((item: string) => ({ value: item })));
        } catch (error) {
            console.error(`获取${field}建议失败:`, error);
            cb([]);
        }
    };
}

// 查询商品信息
async function searchGoods() {
    try {
        loading.value = true;
        const response = await axios.get('/api/goods', {
            params: {
                ...queryForm,
                page: 1,
                pageSize: 1000 // 假设最大查询1000条数据
            }
        });
        goodsList.value = response.data.items;
        total.value = response.data.total;
        currentPage.value = 1;
        ElMessage.success('查询商品信息成功');
    } catch (error) {
        console.error('查询商品信息失败:', error);
        ElMessage.error('查询商品信息失败');
    } finally {
        loading.value = false;
    }
}

// 分页变化
function handlePageChange(page: number) {
    currentPage.value = page;
}

function handleSizeChange(size: number) {
    pageSize.value = size;
    currentPage.value = 1;
}

const addGoodsDialog = ref();
const editGoodsDialog = ref();
const deleteGoodsDialog = ref();

// 打开新建对话框
function openAddDialog() {
    addGoodsDialog.value.openDialog({
        title: '新建商品信息记录',
        formItems: [
            { label: '商品名称', prop: 'goods_name', value: '', rules: [
                { required: true, message: '商品名称不能为空', trigger: 'blur' },
                { max: 50, message: '商品名称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '商品类型', prop: 'goods_type', value: '', rules: [
                { required: true, message: '商品类型不能为空', trigger: 'blur' },
                { max: 50, message: '商品类型长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: '', rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            addGoodsDialog.value.visible = false;
            ElMessage({
                message: '已取消新建',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await addGoodsDialog.value.formRef.validate();
                await axios.post('/api/goods', addGoodsDialog.value.formData);
                ElMessage({
                    message: '新建商品信息记录成功',
                    type: 'success',
                });
                addGoodsDialog.value.visible = false;
                searchGoods();
            } catch (error) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败',
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 打开编辑对话框
function openEditDialog(row: Goods) {
    editGoodsDialog.value.openDialog({
        title: '编辑商品信息记录',
        formItems: [
            { label: '商品名称', prop: 'goods_name', value: row.goods_name, rules: [
                { required: true, message: '商品名称不能为空', trigger: 'blur' },
                { max: 50, message: '商品名称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '商品类型', prop: 'goods_type', value: row.goods_type, rules: [
                { required: true, message: '商品类型不能为空', trigger: 'blur' },
                { max: 50, message: '商品类型长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: row.remarks, rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            editGoodsDialog.value.visible = false;
            ElMessage({
                message: '已取消编辑',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await editGoodsDialog.value.formRef.validate();
                await axios.put(`/api/goods/${row.goods_id}`, editGoodsDialog.value.formData);
                ElMessage({
                    message: '编辑商品信息记录成功',
                    type: 'success',
                });
                editGoodsDialog.value.visible = false;
                searchGoods();
            } catch (error) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败',
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 打开删除对话框
function openDeleteDialog(row: Goods) {
    deleteGoodsDialog.value.openDialog({
        title: '删除商品信息记录',
        content: `是否删除商品ID为 ${row.goods_id} 的记录？`,
        handleCancel: () => {
            deleteGoodsDialog.value.visible = false;
            ElMessage({
                message: '已取消删除',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await axios.delete(`/api/goods/${row.goods_id}`);
                ElMessage({
                    message: '删除商品信息记录成功',
                    type: 'success',
                });
                deleteGoodsDialog.value.visible = false;
                searchGoods();
            } catch (error) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败',
                    type: 'error',
                });
            }
        }
    });
}

onMounted(() => {
    // 初始化时加载数据
    searchGoods();
});
</script>

<style scoped>
.el-form-item {
    margin: 10px 0;
}
.el-input,
.el-button {
    width: 100%;
}
.el-form {
    padding: 20px;
}
.el-form-item .el-form-item__label {
    padding-right: 20px;
}
</style>